import { useMockStore } from "@/stores/mock";
import service from "./config/request";
import { ApiResponse } from "./type";
import { dayjs } from "element-plus";
console.log(service);
export interface IRole {
  id: number;
  name: string;
  description: string;
  is_default?: number;
}

export interface IRoleStatus {
  roles: IRole[];
  count: number;
}

export interface IRoleParam {
  pageSize: number;
  pageNum: number;
}

const mockStore = useMockStore();

// 获取角色列表
export const getRoles = (
  params: IRoleParam = { pageNum: 1, pageSize: 10 }
): Promise<ApiResponse<IRoleStatus>> => {
  // return service.get("/role", { params });
  console.log(params);
  const roles = mockStore.roleList.slice(
    (params.pageNum - 1) * params.pageSize,
    params.pageNum * params.pageSize
  );

  return Promise.resolve({
    data: {
      roles: roles,
      count: mockStore.roleList.length
    },
    code: 0
  });
};

// 新增
export const addRole = (data: IRole): Promise<ApiResponse> => {
  // return service.post("/role", data);
  if (!data.id) {
    data.id = dayjs().unix();
  }
  mockStore.addToList(data, "roleList");
  return Promise.resolve({
    data: "ok",
    code: 0
  });
};

// 修改
export const updateRole = (
  id: number,
  data: Partial<IRole>
): Promise<ApiResponse> => {
  // return service.put("/role/" + id, data);
  const index = (mockStore.roleList as IRole[]).findIndex(
    (item) => item?.id == id
  );
  const roleData = {
    ...(mockStore.roleList[index] as IRole[]),
    ...data
  };
  // mockStore.roleList.splice(index, 1, roleData);
  mockStore.updateToList(roleData, index, "roleList");
  return Promise.resolve({
    data: "ok",
    code: 0
  });
};

// 删除
export const removeRole = (id: number): Promise<ApiResponse> => {
  // return service.delete("/role/" + id);
  const index = (mockStore.roleList as IRole[]).findIndex(
    (item) => item.id == id
  );
  if (index >= 0) {
    mockStore.updateToList(null, index, "roleList");
    return Promise.resolve({
      data: "ok",
      code: 0
    });
  } else {
    return Promise.reject({
      data: "nook",
      code: 1
    });
  }
};
